package com.commons.dbutils.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang.Validate;

/**
 * 支持SHA-1/MD5消息摘要的工具类.
 * 
 * 返回ByteSource，可进一步被编码为Hex, Base64或UrlSafeBase64
 * 
 */
public class Digests {

	private static final String SHA1 = "SHA-1";
	private static final String MD5 = "MD5";
	private static final String Encoding = "GB2312";
    private static final String AES = "AES";
    private static final char[] legalChars =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
            .toCharArray();
	private static SecureRandom random = new SecureRandom();
	private static final char[] BCDLOOKUP_Y = { '0', '1', '2', '3', '4', '5',
		'6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f' };
	/**
	 * 对输入字符串进行sha1散列.
	 */
	public static byte[] sha1(byte[] input) {
		return digest(input, SHA1, null, 1);
	}

	public static byte[] sha1(byte[] input, byte[] salt) {
		return digest(input, SHA1, salt, 1);
	}

	public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
		return digest(input, SHA1, salt, iterations);
	}

	/**
	 * 对字符串进行散列, 支持md5与sha1算法.
	 */
	private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
		try {
			MessageDigest digest = MessageDigest.getInstance(algorithm);

			if (salt != null) {
				digest.update(salt);
			}

			byte[] result = digest.digest(input);

			for (int i = 1; i < iterations; i++) {
				digest.reset();
				result = digest.digest(result);
			}
			return result;
		} catch (GeneralSecurityException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 生成随机的Byte[]作为salt.
	 * 
	 * @param numBytes byte数组的大小
	 */
	public static byte[] generateSalt(int numBytes) {
		Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);

		byte[] bytes = new byte[numBytes];
		random.nextBytes(bytes);
		return bytes;
	}

	/**
	 * 对文件进行md5散列.
	 */
	public static byte[] md5(InputStream input) throws IOException {
		return digest(input, MD5);
	}

	/**
	 * 对文件进行sha1散列.
	 */
	public static byte[] sha1(InputStream input) throws IOException {
		return digest(input, SHA1);
	}

	private static byte[] digest(InputStream input, String algorithm) throws IOException {
		try {
			MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
			int bufferLength = 8 * 1024;
			byte[] buffer = new byte[bufferLength];
			int read = input.read(buffer, 0, bufferLength);

			while (read > -1) {
				messageDigest.update(buffer, 0, read);
				read = input.read(buffer, 0, bufferLength);
			}

			return messageDigest.digest();
		} catch (GeneralSecurityException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将字节数组转换成16进制的字符串
	 * @param bts
	 * @return
	 */
	private static String bytes2Hex(byte[] bts) {
		StringBuffer des = new StringBuffer();
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des.append("0");
			}
			des.append(tmp);
		}
		return des.toString();
	}

	public static String md5(String input) {
		try {
			return bytes2Hex(md5(new ByteArrayInputStream(input.getBytes())));
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}
	
	/**
	 * ASE解密
	 * @param strSrcString 解密字符串
	 * @param strPassword  解密密钥
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String strSrcString,String strPassword)
	        throws Exception {
		if(null == strSrcString || strSrcString.trim().length() < 1) {
		    return null;
		}
		strPassword = generateKey(strPassword);
		byte[] raw = strPassword.getBytes(Encoding);
		SecretKeySpec skeySpec = new SecretKeySpec(raw,AES);
		Cipher cipher = Cipher.getInstance(AES);
		cipher.init(Cipher.DECRYPT_MODE,skeySpec);
		byte[] encrypted1 = base64Decode(strSrcString);
		byte[] original = cipher.doFinal(encrypted1);
		String originalString = new String(original);
		return originalString;
	} 
	
	/**
	 * ASE加密
	 * @param strSrcString 加密字符串
	 * @param strPassword 加密密钥
	 * @return
	 */
	public static String encrypt(String strSrcString,String strPassword) {
		try {
		    if(null == strSrcString || strSrcString.trim().length() < 1){
		        return null;
		    }
		    strPassword = generateKey(strPassword);
		    byte[] raw = strPassword.getBytes(Encoding);
		    SecretKeySpec skeySpec = new SecretKeySpec(raw,AES);
		    Cipher cipher = Cipher.getInstance(AES);
		    cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
		    byte[] encrypted = cipher.doFinal(strSrcString.getBytes());
		    return base64Encode(encrypted);
		} catch(Exception ex){
			return "";
		}
    } 
	
	private static String generateKey(String str)
	        throws NoSuchAlgorithmException,UnsupportedEncodingException {
		if(null == str) {
		    str = "defaultpassword";
		} else if(str.length() < 1) {
		    str = "emptypassword";
		}
		java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
		md.update(str.getBytes(Encoding));
		String strret = base64Encode(md.digest());
		while(strret.length() < 16) {
		    strret += "%";
		}
		if(strret.length() > 16) {
		    int nbegin = (strret.length() - 16) / 2;
		    strret = strret.substring(nbegin,nbegin + 16);
		}
		return strret;
	} 
	
	/** Base64 encode the given data */
    public static String base64Encode(byte[] data) {
        int start = 0;
        int len = data.length;
        StringBuffer buf = new StringBuffer(data.length * 3 / 2);
 
        int end = len - 3;
        int i = start;
        int n = 0;
 
        while (i <= end) {
            int d = ((((int) data[i]) & 0x0ff) << 16)
                    | ((((int) data[i + 1]) & 0x0ff) << 8)
                    | (((int) data[i + 2]) & 0x0ff);
 
            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append(legalChars[(d >> 6) & 63]);
            buf.append(legalChars[d & 63]);
 
            i += 3;
 
            if (n++ >= 14) {
                n = 0;
                buf.append(" ");
            }
        }
 
        if (i == start + len - 2) {
            int d = ((((int) data[i]) & 0x0ff) << 16)
                    | ((((int) data[i + 1]) & 255) << 8);
 
            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append(legalChars[(d >> 6) & 63]);
            buf.append("=");
        } else if (i == start + len - 1) {
            int d = (((int) data[i]) & 0x0ff) << 16;
 
            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append("==");
        }
 
        return buf.toString();
    }
    
    /**
     * Decodes the given Base64 encoded String to a new byte array. The byte
     * array holding the decoded data is returned.
     */
 
    public static byte[] base64Decode(String s) {
 
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
        	base64Decode(s, bos);
        } catch (IOException e) {
            throw new RuntimeException();
        }
        byte[] decodedBytes = bos.toByteArray();
        try {
            bos.close();
            bos = null;
        } catch (IOException ex) {
            System.err.println("Error while decoding BASE64: " + ex.toString());
        }
        return decodedBytes;
    }
 
    private static void base64Decode(String s, OutputStream os) throws IOException {
        int i = 0;
 
        int len = s.length();
 
        while (true) {
            while (i < len && s.charAt(i) <= ' ') {
                i++;
            }
 
            if (i == len) {
                break;
            }
 
            int tri = (base64Decode(s.charAt(i)) << 18)
                      + (base64Decode(s.charAt(i + 1)) << 12)
                      + (base64Decode(s.charAt(i + 2)) << 6)
                      + (base64Decode(s.charAt(i + 3)));
 
            os.write((tri >> 16) & 255);
            if (s.charAt(i + 2) == '=') {
                break;
            }
            os.write((tri >> 8) & 255);
            if (s.charAt(i + 3) == '=') {
                break;
            }
            os.write(tri & 255);
 
            i += 4;
        }
    }
    
    private static int base64Decode(char c) {
        if (c >= 'A' && c <= 'Z') {
            return ((int) c) - 65;
        } else if (c >= 'a' && c <= 'z') {
            return ((int) c) - 97 + 26;
        } else if (c >= '0' && c <= '9') {
            return ((int) c) - 48 + 26 + 26;
        } else {
            switch (c) {
            case '+':
                return 62;
            case '/':
                return 63;
            case '=':
                return 0;
            default:
                throw new RuntimeException("unexpected code: " + c);
            }
        }
    }
    
    /**
	 * 15位身份证转18位身份证
	 * @description:
	 * 1.身份证15位转18位原理：身份证中的年份补全，即：
	 * 第六、七位之间增加“1”“9”（目前大多数是20世纪出身的），现在身份证号码位数是17位
	 * 2.第18位确定：将身份证号码17位数分别乘以不同系数，为7-9-10-5-8-4-2-1-6-3-7-9-10-5-8-4-2
	 * 3.将这17位数字相加除以11，得到余数
	 * 4.余数只可能为0-1-2-3-4-5-6-7-8-9-10这11个数字。其分别对应的数为1-0-X-9-8-7-6-5-4-3-2
	 * 而这个数就是最后一位身份证号码
	 * @param idCard15
	 * @return
	 */
	public static String idCardConvert(String idCard) {
		if(idCard.length() > 15){
			return idCard;
		}
		StringBuffer idCard18 = new StringBuffer(idCard);
		idCard18 = idCard18.insert(6, "19");
		idCard18.append(doVerify(idCard18.toString()));
		return idCard18.toString();
    }

	public static char doVerify(String id) { // 最后一位效验码生成
		char src[] = id.toCharArray();
		int sum = 0;
		int iW[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
		char verCode[] = new char[] { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
		int i;
		 for (i = 0; i < id.length(); i++) {
		    sum += (src[i] - '0') * iW[i];
		}
		int iY = sum % 11;
		return verCode[iY];
    }
	public static String[] bubbleSort(String[] r) {
		int i, j; // 交换标志
		String temp;
		Boolean exchange;
		for (i = 0; i < r.length; i++) // 最多做R.Length-1趟排序
		{
			exchange = false; // 本趟排序开始前，交换标志应为假
			for (j = r.length - 2; j >= i; j--) {
				if (r[j + 1].compareTo(r[j]) < 0)// 交换条件
				{
					temp = r[j + 1];
					r[j + 1] = r[j];
					r[j] = temp;
					exchange = true; // 发生了交换，故将交换标志置为真
				}
			}
			if (!exchange) // 本趟排序未发生交换，提前终止算法
			{
				break;
			}
		}
		return r;

	}
	public static String getMD5ByArray(String[] sortedstr, String key,
			String inputCharset) {
		// 构造待md5摘要字符串
		StringBuilder prestr = new StringBuilder();
		for (int i = 0; i < sortedstr.length; i++) {
			if (i == sortedstr.length - 1) {
				prestr.append(sortedstr[i]);
			} else {
				prestr.append(sortedstr[i] + "&");
			}
		}
		prestr.append(key);
		// 此处key为上面的innerKey
		return getMD5(prestr.toString(), inputCharset);
	}
	public static String getMD5(String source, String inputCharset) {
		String s = null;
		// 用来将字节转换成 16 进制表示的字符
//		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
//				'a', 'b', 'c', 'd', 'e', 'f' };
		MessageDigest md = null;
		byte[] tmp =null;
		// 用字节表示就是 16 个字节
		char str[] = new char[16 * 2];
		// 每个字节用 16 进制表示的话，使用两个字符，
		int k = 0; // 表示转换结果中对应的字符位置
		byte byte0=0;
		try {
			md = MessageDigest.getInstance("MD5");
			md.update(source.getBytes(inputCharset));
			tmp = md.digest();
			// MD5 的计算结果是一个 128 位的长整数，
			
			for (int i = 0; i < 16; i++) {
				// 从第一个字节开始，对 MD5 的每一个字节
				// 转换成 16 进制字符的转换
				byte0 = tmp[i];
				// 取第 i 个字节
				str[k++] = BCDLOOKUP_Y[byte0 >>> 4 & 0xf];
				// 取字节中高 4 位的数字转换,
				// >>> 为逻辑右移，将符号位一起右移
				str[k++] = BCDLOOKUP_Y[byte0 & 0xf];
				// 取字节中低 4 位的数字转换
			}
			s = new String(str);
			// 换后的结果转换为字符串
		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}
}
